package Controller;

import Util.ImageCut;
import Util.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.Random;

/**
 * Created by F on 2017/2/28.
 */

@Controller
public class ImgCutController {

    @ResponseBody
    @RequestMapping(value = "/imgCut",method = RequestMethod.POST, produces="text/html;charset=utf-8")
    public String profile_imgCut(MultipartFile avatar_file, String avatar_data) {
        String path = "src/main/resources/static/images/";

        //判断文件类型
        String type = avatar_file.getContentType();
        if(type==null || !type.toLowerCase().startsWith("image/")) return  JSON.toJSONString(new Result(false,"不支持的文件类型，仅支持图片！"));

        String name = avatar_file.getOriginalFilename();
        String fileName = new Date().getTime()+""+new Random().nextInt(10000)+name.substring(name.lastIndexOf('.'));

        JSONObject joData = (JSONObject) JSONObject.parse(avatar_data);
        // 用户经过剪辑后的图片的大小
        float x = joData.getFloatValue("x");
        float y = joData.getFloatValue("y");
        float w =  joData.getFloatValue("width");
        float h =  joData.getFloatValue("height");

        //开始上传
        File targetFile = new File(path, fileName);
        //保存
        try {
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            InputStream is = avatar_file.getInputStream();
            ImageCut.cut(is, targetFile, (int)x,(int)y,(int)w,(int)h);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
            return  JSON.toJSONString(new Result(false,"上传失败，出现异常："+e.getMessage()));
        }

        return  JSON.toJSONString(new Result(true,"上传成功!","images/"+fileName));
    }
}
